﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using System.Web.UI;
using IssueIT.WebUI.Infrastructure;
using IssueIT.WebUI.Models;
using Onesoft.StampShop.Helpers;

namespace IssueIT.WebUI.Controllers
{
    public class ImageController : Controller
    {
        //
        // GET: /Image/
        private ImageSettings _settings;

        public ImageController(ImageSettings imageSettings)
        {
            _settings = imageSettings;
        }

        private class ImageFileInfo
        {
            private string _id;
            private string _size;
            private string _cacheDir;
            private string _cacheDirAndImage;

            private string _sourceDir;
            private string _sourceUri;

            private readonly ImageSettings _imageSettings;

            public ImageFileInfo(string id, string size, ImageSettings imageSettings)
            {
                _id = id;
                _size = size;
                _imageSettings = imageSettings;
                //_server = server;
            }

            public string SourceUri
            {
                get
                {
                    if (string.IsNullOrEmpty(_sourceUri))
                    {
                        _sourceUri = Path.Combine(SourceDir, _id + ".jpg");
                    }

                    return _sourceUri;
                }
            }

            public string SourceDir
            {
                get
                {
                    if (string.IsNullOrEmpty(_sourceDir))
                    {
                        _sourceDir = _imageSettings.ImageDataDir;

                    }

                    return _sourceDir;
                }
            }

            /// <summary>
            /// Gets the full sti to the cahced image including the image name
            /// </summary>
            public string CacheUri
            {
                get
                {
                    if (string.IsNullOrEmpty(_cacheDirAndImage))
                        _cacheDirAndImage = Path.Combine(CacheDir, string.Concat(_size, ".jpg"));

                    return _cacheDirAndImage;
                }
            }

            public string CacheDir
            {
                get
                {
                    if (string.IsNullOrEmpty(_cacheDir))
                    {
                        var tmp = string.Concat(_id.Substring(_id.Length - 1), @"\", _id);
                        //TODO: ændre til |datadir..eller setting|
                        
                        _cacheDir = Path.Combine(_imageSettings.CacheDir, tmp);
                    }

                    return _cacheDir;
                }
            }

        }

        [OutputCache(Location = OutputCacheLocation.Any, VaryByParam = "*", Duration = 31556926)]
        public FilePathResult Get(string id, string size)
        {
            ImageSize requestedSettimgs = _settings.GetImageSize(size);

            var imageFileInfo = new ImageFileInfo(id, size, _settings);

            if (!System.IO.File.Exists(imageFileInfo.CacheUri))
            {
                //todo: noImage fra settings
                if (!System.IO.File.Exists(imageFileInfo.SourceUri))
                {
                    //todo: is 404 error better?
                    throw new FileNotFoundException(imageFileInfo.SourceUri);
                }
                //todo:
                //return File(Path.Combine(dir, "NoImage.jpg"), "image/jpeg");

                using (var sourceImg = Image.FromFile(imageFileInfo.SourceUri))
                {
                    var helper = new PictureHelper();
                    using (
                        var newImg = helper.ResizeImage(sourceImg, requestedSettimgs.Size, CanvasType.Fixed,
                                                        requestedSettimgs.BackgroundColor))
                    {
                        SaveCachedImage(imageFileInfo, helper, requestedSettimgs, newImg);
                    }
                }
            }

            return File(imageFileInfo.CacheUri, "image/jpeg");
        }

        private void SaveCachedImage(ImageFileInfo imageFileInfo, PictureHelper helper, ImageSize requestedSize, Image newImg)
        {
            if (!Directory.Exists(imageFileInfo.CacheDir))
            {
                Directory.CreateDirectory(imageFileInfo.CacheDir);
            }

            int compression = ResolveCompression(requestedSize.Size);

            ImageCodecInfo codecInfo = helper.GetEncoderInfo(ImageFormat.Jpeg);
            EncoderParameters encParams = new EncoderParameters();
            encParams.Param[0] = new EncoderParameter(Encoder.Quality, compression);
            newImg.Save(imageFileInfo.CacheUri, codecInfo, encParams);
        }

        private int ResolveCompression(Size imageSize)
        {
            if (imageSize.Height <= 100 && imageSize.Width <= 100)
                return 85;

            return 80; 
        }

    }
}
